<template>
  <el-dialog
    v-model="visible"
    title="入院登记"
    width="520px"
    append-to-body
    :close-on-click-modal="true"
    :show-close="true"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="86px">
      <el-form-item label="患者">
        <span>{{ form.patientName || '-' }}</span>
      </el-form-item>
      <el-form-item label="科室">
        <span>{{ form.deptName || '-' }}</span>
      </el-form-item>
      <el-form-item label="病区">
        <span>{{ form.wardName || '-' }}</span>
      </el-form-item>
      <el-form-item label="入院时间" prop="admissionDate">
        <div class="admission-time-group">
          <el-date-picker
            v-model="form.admissionDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            style="width: 180px"
          />
          <el-time-picker
            v-model="form.admissionTime"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="请选择时间"
            style="width: 120px; margin-left: 8px"
          />
        </div>
      </el-form-item>
      <el-form-item label="预缴押金" prop="deposit">
        <!-- 中文注释：允许输入两位小数；最小值为 0；非必填 -->
        <el-input-number
          v-model="form.deposit"
          :min="0"
          :step="1"
          :precision="2"
          controls-position="right"
          placeholder="请输入押金"
          style="width: 180px"
        >
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">登记</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="AdmissionHandleDialog">
// 中文注释：使用 Vue3 Composition API 实现弹窗与表单逻辑
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  initialData: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['update:modelValue', 'submit', 'cancel'])

// 中文注释：响应式控制弹窗显隐
const visible = computed({
  get: () => props.modelValue,
  set: val => emits('update:modelValue', val)
})

// 中文注释：将初始数据映射到内部表单模型；分离日期与时间以适配参照图
const formRef = ref(null)
const form = reactive({
  patientName: '',
  deptName: '',
  wardName: '',
  admissionDate: '',
  admissionTime: '',
  deposit: 0
})

// 中文注释：将 Date 默认值拆分为日期（YYYY-MM-DD）与时间（HH:mm）
const formatDate = d => {
  const yyyy = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}
const formatTime = d => {
  const hh = String(d.getHours()).padStart(2, '0')
  const mi = String(d.getMinutes()).padStart(2, '0')
  return `${hh}:${mi}`
}

// 中文注释：监听 props 初始数据以填充表单
watch(
  () => props.initialData,
  val => {
    const now = val?.admissionAt instanceof Date ? val.admissionAt : new Date()
    form.patientName = val?.patientName ?? ''
    form.deptName = val?.deptName ?? ''
    form.wardName = val?.wardName ?? ''
    form.admissionDate = val?.admissionDate ?? formatDate(now)
    form.admissionTime = val?.admissionTime ?? formatTime(now)
    form.deposit = Number.isFinite(val?.deposit) ? Number(val.deposit) : 0
  },
  { immediate: true, deep: true }
)

// 中文注释：自定义校验——押金非必填；若填写需为非负且最多两位小数
const validateAmount = (rule, value, callback) => {
  if (value === undefined || value === null || value === '') return callback()
  const n = Number(value)
  if (!Number.isFinite(n)) return callback(new Error('请输入数字'))
  if (n < 0) return callback(new Error('最小值为 0'))
  const text = String(value)
  const decimals = text.includes('.') ? text.split('.')[1] : ''
  if (decimals && decimals.length > 2) return callback(new Error('仅允许输入两位小数'))
  return callback()
}

// 中文注释：表单校验规则
const rules = reactive({
  admissionDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
  deposit: [{ validator: validateAmount, trigger: ['change', 'blur'] }]
})

// 中文注释：组合日期与时间为完整字符串，供外部提交
const buildAdmissionAt = () => {
  const date = form.admissionDate || formatDate(new Date())
  const time = form.admissionTime || formatTime(new Date())
  return `${date} ${time}:00`
}

// 中文注释：提交事件，先进行校验，成功后抛出统一数据结构
const handleSubmit = () => {
  formRef.value?.validate(valid => {
    if (!valid) return
    emits('submit', {
      patientName: form.patientName,
      deptName: form.deptName,
      wardName: form.wardName,
      admissionAt: buildAdmissionAt(),
      deposit: Number(form.deposit)
    })
    visible.value = false
  })
}

// 中文注释：取消事件，关闭弹窗并通知父级
const handleCancel = () => {
  visible.value = false
  emits('cancel')
}
</script>

<style scoped lang="scss">
.admission-time-group {
  display: flex;
  align-items: center;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>
